package com.xiaofeng.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.xiaofeng.subject.common.entity.PageResult;
import com.xiaofeng.subject.common.enums.IsDeletedFlagEnum;
import com.xiaofeng.subject.common.utils.IdWorkerUtil;
import com.xiaofeng.subject.common.utils.LoginUtil;
import com.xiaofeng.subject.domain.convert.SubjectInfoConverter;
import com.xiaofeng.subject.domain.entity.SubjectInfoBO;
import com.xiaofeng.subject.domain.entity.SubjectOptionBO;
import com.xiaofeng.subject.domain.handler.subject.SubjectTypeHandler;
import com.xiaofeng.subject.domain.handler.subject.SubjectTypeHandlerFactory;
import com.xiaofeng.subject.domain.redis.RedisUtil;
import com.xiaofeng.subject.domain.service.SubjectInfoDomainService;
import com.xiaofeng.subject.domain.service.SubjectLikedDomainService;
import com.xiaofeng.subject.infra.basic.entity.SubjectInfo;
import com.xiaofeng.subject.infra.basic.entity.SubjectInfoEs;
import com.xiaofeng.subject.infra.basic.entity.SubjectLabel;
import com.xiaofeng.subject.infra.basic.entity.SubjectMapping;
import com.xiaofeng.subject.infra.basic.service.SubjectEsService;
import com.xiaofeng.subject.infra.basic.service.SubjectInfoService;
import com.xiaofeng.subject.infra.basic.service.SubjectLabelService;
import com.xiaofeng.subject.infra.basic.service.SubjectMappingService;
import com.xiaofeng.subject.infra.entity.UserInfo;
import com.xiaofeng.subject.infra.rpc.UserRpc;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA
 *
 * @Author: chc
 * @Date: 2024/01/27/12:04
 * @Description:
 */
@Service
@Slf4j
public class SubjectInfoDomainServiceImpl implements SubjectInfoDomainService {

    @Resource
    private SubjectInfoService subjectInfoService;

    @Resource
    private SubjectMappingService subjectMappingService;

    @Resource
    private SubjectLabelService subjectLabelService;

    @Resource
    public SubjectTypeHandlerFactory subjectTypeHandlerFactory;

    @Resource
    private SubjectEsService subjectEsService;

    @Resource
    private SubjectLikedDomainService subjectLikedDomainService;

    @Resource
    private UserRpc userRpc;

    @Resource
    private RedisUtil redisUtil;

    private static final String RANK_KEY = "subject_rank";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SubjectInfoBO subjectInfoBO) {
        if(log.isInfoEnabled()){
            log.info("SubjectInfoDomainServiceImpl.add.bo:{}", JSON.toJSONString(subjectInfoBO));
        }
        //工厂+策略模式
        // 1.题目信息插入
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBOToInfo(subjectInfoBO);
        subjectInfo.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        subjectInfoService.insert(subjectInfo);
        // 2.题目答案插入
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        subjectInfoBO.setId(subjectInfo.getId());
        handler.add(subjectInfoBO);
        //分类id集合
        List<Integer> categoryIds = subjectInfoBO.getCategoryIds();
        //标签id集合
        List<Integer> labelIds = subjectInfoBO.getLabelIds();
        //创建一个SubjectMapping类型的list集合
        List<SubjectMapping> mappingList = new LinkedList<>();
        //循环遍历分类id
        categoryIds.forEach(categoryId ->{
            //循环遍历出标签id
            labelIds.forEach(labelId ->{
                SubjectMapping subjectMapping = new SubjectMapping();
                subjectMapping.setSubjectId(subjectInfo.getId());
                subjectMapping.setCategoryId(Long.valueOf(categoryId));
                subjectMapping.setLabelId(Long.valueOf(labelId));
                subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
                mappingList.add(subjectMapping);
            });
        });
        //批量插入
        subjectMappingService.batchInsert(mappingList);
        //同步到es中
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        subjectInfoEs.setDocId(new IdWorkerUtil(1,1,1).nextId());
        subjectInfoEs.setSubjectId(subjectInfo.getId());
        subjectInfoEs.setSubjectAnswer(subjectInfoBO.getSubjectAnswer());
        subjectInfoEs.setCreateTime(new Date().getTime());
        subjectInfoEs.setCreateUser("晓风");
        subjectInfoEs.setSubjectName(subjectInfo.getSubjectName());
        subjectInfoEs.setSubjectType(subjectInfo.getSubjectType());
        //插入到es中
        subjectEsService.insert(subjectInfoEs);
        //redis放入zadd计入排行榜
        redisUtil.addScore(RANK_KEY, LoginUtil.getLoginId(),1);
    }

    @Override
    public PageResult<SubjectInfoBO> getSubjectPage(SubjectInfoBO subjectInfoBO) {
        //分页对象
        PageResult<SubjectInfoBO> pageResult = new PageResult<>();
        //设置页码、页数
        pageResult.setPageNo(subjectInfoBO.getPageNo());
        pageResult.setPageSize(subjectInfoBO.getPageSize());
        int start = ( subjectInfoBO.getPageNo() - 1) * subjectInfoBO.getPageSize();
        //将SubjectInfoBO转换为SubjectInfo
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBOToInfo(subjectInfoBO);
        //查询总条数
        int count = subjectInfoService.countByCondition(subjectInfo,subjectInfoBO.getCategoryId(),subjectInfoBO.getLabelId());
        if (count == 0){
            return pageResult;
        }
        //分页查询题目信息(包括题目和答案)
        List<SubjectInfo> subjectInfoList =  subjectInfoService.queryPage(subjectInfo,subjectInfoBO.getCategoryId(),subjectInfoBO.getLabelId(),start,subjectInfoBO.getPageSize());
        //将List<SubjectInfo>转换List<SubjectInfoBO>
        List<SubjectInfoBO> subjectInfoBOS = SubjectInfoConverter.INSTANCE.convertListInfoToBO(subjectInfoList);
        //分页数据
        pageResult.setRecords(subjectInfoBOS);
        //分页总数
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public SubjectInfoBO querySubjectInfo(SubjectInfoBO subjectInfoBO) {
        //通过题目信息id查询题目信息，判断是那种类型的题型
        SubjectInfo subjectInfo = subjectInfoService.queryById(subjectInfoBO.getId());
        //工厂+策略模式
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        //查询题目选择的答案
        SubjectOptionBO optionBO = handler.query(subjectInfo.getId().intValue());
        //转换
        SubjectInfoBO bo = SubjectInfoConverter.INSTANCE.convertOptionAndInfoToBO(optionBO, subjectInfo);
        //创建SubjectMapping对象
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setSubjectId(subjectInfo.getId());
        subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        //查询题目属于那种标签的id
        List<SubjectMapping> mappingList = subjectMappingService.queryLabelId(subjectMapping);
        //循环遍历id集合
        List<Long> labelIdList = mappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        //批量查询
        List<SubjectLabel> labelList = subjectLabelService.batchQueryById(labelIdList);
        //获取标签名称集合
        List<String> labelNameList = labelList.stream().map(SubjectLabel::getLabelName).collect(Collectors.toList());
        //添加到bo里面
        bo.setLabelName(labelNameList);
        bo.setLiked(subjectLikedDomainService.isLiked(subjectInfoBO.getId().toString(), LoginUtil.getLoginId()));
        bo.setLikedCount(subjectLikedDomainService.getLikedCount(subjectInfoBO.getId().toString()));
        assembleSubjectCursor(subjectInfoBO,bo);
        //返回数据
        return bo;
    }

    private void assembleSubjectCursor(SubjectInfoBO subjectInfoBO, SubjectInfoBO bo) {
        //获取分类id
        Integer categoryId = subjectInfoBO.getCategoryId();
        //获取标签id
        Long labelId = subjectInfoBO.getLabelId();
        //获取题目id
        Long subjectId = subjectInfoBO.getId();
        if (Objects.isNull(subjectId) || Objects.isNull(labelId)){
            return;
        }
        //下一题
        Long nextSubjectId = subjectInfoService.querySubjectIdCursor(subjectId, categoryId,labelId,1);
        bo.setNextSubjectId(nextSubjectId);
        //上一题
        Long lastSubjectId = subjectInfoService.querySubjectIdCursor(subjectId, categoryId,labelId,0);
        bo.setLastSubjectId(lastSubjectId);
    }

    @Override
    public PageResult<SubjectInfoEs> getSubjectPageBySearch(SubjectInfoBO subjectInfoBO) {
        //定义ES对象
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        //设置页数
        subjectInfoEs.setPageNo(subjectInfoBO.getPageNo());
        //设置分页数量
        subjectInfoEs.setPageSize(subjectInfoBO.getPageSize());
        //查询的关键字
        subjectInfoEs.setKeyWord(subjectInfoBO.getKeyWord());
        //查询数据
        PageResult<SubjectInfoEs> pageResult = subjectEsService.querySubjectList(subjectInfoEs);
        return pageResult;
    }

    @Override
    public List<SubjectInfoBO> getContributeList() {
        //查询排名前六的数据（按从大到小排）
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisUtil.rankWithScore(RANK_KEY, 0, 5);
        if (log.isInfoEnabled()) {
            log.info("getContributeList.typedTuples:{}", JSON.toJSONString(typedTuples));
        }
        //根据题目创建人查询出题数
        List<SubjectInfo> subjectInfoList = subjectInfoService.getContributeCount();
        //判断是否为空
        if(CollectionUtils.isEmpty(subjectInfoList)){
            return Collections.emptyList();
        }
        LinkedList<SubjectInfoBO> boList = new LinkedList<>();
        //Foreach循环遍历
        subjectInfoList.forEach(subjectInfo ->{
            //创建一个SubjectInfoBo对象
            SubjectInfoBO subjectInfoBO = new SubjectInfoBO();
            //设置数量
            subjectInfoBO.setSubjectCount(subjectInfo.getSubjectCount());
            UserInfo userInfo = userRpc.getUserInfo(subjectInfo.getCreatedBy());
            //设置创建该题目的创建人用户名
            subjectInfoBO.setCreateUser(userInfo.getNickName());
            //设置创建该题目的创建人头像
            subjectInfoBO.setCreateUserAvatar(userInfo.getAvatar());
            //添加到集合中
            boList.add(subjectInfoBO);
        });
        //返回集合
        return boList;
    }

}
